package com.robotlab.easytranslate.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Build;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.robotlab.easytranslate.R;
import com.robotlab.easytranslate.dbase.Wordbook;
import com.robotlab.easytranslate.util.HttpUtil;
import com.robotlab.easytranslate.util.JinshanParseUtil;
import com.robotlab.easytranslate.util.NetWorkUtil;
import com.robotlab.easytranslate.util.StringUtil;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ProcessTextActivity extends Activity {

    private TextView tv_output,tv_input,tv_input_language,tv_output_language;
    private ImageButton ib_sound,ib_copy,ib_close;
    private CheckBox cb_collect;
    private LinearLayout ll_more;
    private String voiceUrl = null;
    private Boolean isCollect = false;
    private String QuereText, MeanText, VoiceText, VoiceTextUrl;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_process_text);
        initView();
        checkText(getIntent());
    }

    private void initView() {
        if (Build.VERSION.SDK_INT >=21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        tv_output = findViewById(R.id.TV_output);
        tv_input = findViewById(R.id.TV_input);
        tv_input_language = findViewById(R.id.tv_language_input);
        tv_output_language = findViewById(R.id.tv_language_output);
        ib_close = findViewById(R.id.ib_close);
        cb_collect = findViewById(R.id.IB_collect);
        ib_copy = findViewById(R.id.IB_copy);
        ib_sound = findViewById(R.id.IB_sound);
        ll_more = findViewById(R.id.ll_more);
        ib_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        ll_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String data = tv_input.getText().toString();
                Intent intent = new Intent(ProcessTextActivity.this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("input_text", data);
                finish();
                startActivity(intent);
            }
        });
        ib_sound.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (voiceUrl != null && voiceUrl != "空") {
                    try {
                        MediaPlayer mediaPlayer = new MediaPlayer();
                        mediaPlayer.setDataSource(voiceUrl);
                        mediaPlayer.prepareAsync();
                        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                            @Override
                            public void onPrepared(MediaPlayer mediaPlayer) {
                                mediaPlayer.start();
                            }
                        });
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(ProcessTextActivity.this,"暂无发音",Toast.LENGTH_SHORT).show();
                }
            }
        });
        ib_copy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!tv_output.getText().toString().equals("")) {
                    final ClipboardManager clipboardManager = (ClipboardManager)
                            getSystemService(Context.CLIPBOARD_SERVICE);

                    ClipData clipData = ClipData.newPlainText("Label", tv_output.getText().toString());
                    clipboardManager.setPrimaryClip(clipData);
                    Toast.makeText(ProcessTextActivity.this,"已成功复制到剪切板",Toast.LENGTH_SHORT).show();
                }
            }
        });
        cb_collect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (QuereText != MeanText) {
                    if(isCollect == false) {
                        if (b) {
                            isCollect = true;
                            Wordbook wordbook = new Wordbook();
                            wordbook.setQuereText(QuereText);
                            wordbook.setMeanText(MeanText);
                            wordbook.setVoiceText(VoiceText);
                            wordbook.setVoiceUrlText(VoiceTextUrl);
                            wordbook.save();
                            Toast.makeText(ProcessTextActivity.this, "已收藏到单词本", Toast.LENGTH_SHORT).show();
                        } else {
                            isCollect = false;
                            DataSupport.deleteAll(Wordbook.class, "quereText = ?", QuereText);
                            Toast.makeText(ProcessTextActivity.this, "已从单词本中移除", Toast.LENGTH_SHORT).show();
                        }
                    }else {
                        if (!b) {
                            isCollect = false;
                            DataSupport.deleteAll(Wordbook.class, "quereText = ?", QuereText);
                            Toast.makeText(ProcessTextActivity.this, "已从单词本中移除", Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    if (b) {
                        isCollect = false;
                        Toast.makeText(ProcessTextActivity.this, "翻译失败无法收藏", Toast.LENGTH_SHORT).show();
                        cb_collect.setChecked(false);
                    }
                }
            }
        });
    }

    private void checkText(Intent intent) {
        final CharSequence content = intent.getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT);
        tv_input.setText(content);
        if (NetWorkUtil.isNetConnected(this)) {
            final String text = StringUtil.toLowerCaseFirstOne(content.toString());
            try {
                final String urlxml = "http://dict-co.iciba.com/api/dictionary.php?w=" + text + "&key=9ED0664FFB08623D298EF8E174475567";
                String url = "http://dict-co.iciba.com/api/dictionary.php?w=" + text + "&type=json&key=9ED0664FFB08623D298EF8E174475567";
                if (JinshanParseUtil.isEnglish(text.toString())) {
                    tv_input_language.setText("英语");
                    tv_output_language.setText("中文");
                    HttpUtil.sendOkHttpRequest(urlxml, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Toast.makeText(ProcessTextActivity.this, "获取翻译数据失败！", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            final String result = response.body().string();
                            Log.d("TranslateFragment", result);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    JinshanParseUtil.parseJinshanEnglishToChineseXMLWithPull(result);
                                    SharedPreferences pref = getSharedPreferences("JinshanEnglishToChinese", MODE_PRIVATE);

                                    String queryText = pref.getString("queryText", "空");
                                    String voiceEnText = pref.getString("voiceEnText", "空");
                                    String voiceEnUrlText = pref.getString("voiceEnUrlText", "空");
                                    String voiceAmText = pref.getString("voiceAmText", "空");
                                    String voiceAmUrlText = pref.getString("voiceAmUrlText", "空");
                                    String meanText = pref.getString("meanText", "空");
                                    String exampleText = pref.getString("exampleText", "空");
                                    tv_output.setText("");
                                    if (!queryText.equals(text)) {
                                        tv_output.setText(text);
                                        voiceUrl = null;
                                    } else {
                                        tv_output.setText("");
                                        voiceUrl = voiceAmUrlText;
                                        tv_output.append(meanText);
                                        MeanText = meanText;
                                        VoiceText = voiceAmText;
                                        VoiceTextUrl = voiceUrl;
                                        QuereText = queryText;
                                        List<Wordbook> wordbooks = DataSupport.findAll(Wordbook.class);
                                        for (Wordbook wordbook : wordbooks) {
                                            if (QuereText.equals(wordbook.getQuereText())) {
                                                isCollect = true;
                                                cb_collect.setChecked(true);
                                            } else {
                                                isCollect = false;
                                            }
                                        }
                                    }

                                }
                            });
                        }
                    });
                } else {
                    tv_input_language.setText("中文");
                    tv_output_language.setText("英语");
                    HttpUtil.sendOkHttpRequest(url, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Toast.makeText(ProcessTextActivity.this, "获取翻译数据失败！", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            final String result = response.body().string();
                            Log.e("TranslateFragment", result);

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    JinshanParseUtil.parseJinshanChineseToEnglishJSONWithGson(result);
                                    SharedPreferences pref = getSharedPreferences("JinshanChineseToEnglishBaseMean", MODE_PRIVATE);

                                    String queryText = pref.getString("queryText", "空");
                                    String voiceText = pref.getString("voiceText", "暂无");
                                    String voiceUrlText = pref.getString("voiceUrlText", "空");
                                    String meanText = pref.getString("meanText", "空");
                                    tv_output.setText("");

                                    if (!queryText.equals(text)) {
                                        tv_output.setText(text);
                                        voiceUrl = null;
                                    } else {
                                        tv_output.setText("");
                                        voiceUrl = voiceUrlText;
                                        tv_output.setText(meanText);
                                        MeanText = meanText;
                                        VoiceText = voiceText;
                                        VoiceTextUrl = voiceUrl;
                                        QuereText = queryText;
                                        List<Wordbook> wordbooks = DataSupport.findAll(Wordbook.class);
                                        for (Wordbook wordbook : wordbooks) {
                                            if (QuereText.equals(wordbook.getQuereText())) {
                                                isCollect = true;
                                                cb_collect.setChecked(true);
                                            } else {
                                                isCollect = false;
                                            }
                                        }
                                    }

                                }
                            });

                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            finish();
            Toast.makeText(ProcessTextActivity.this,"请检查网络状态",Toast.LENGTH_SHORT).show();
        }
    }
}
